package com.richie696.bank.system;

import spring.annotations.Autowired;
import spring.context.WebApplicationContext;
import spring.webmvc.ContextLoader;

import javax.servlet.http.HttpServlet;
import java.lang.reflect.Field;
import java.util.Objects;

public abstract class AbstractServlet extends HttpServlet {

    protected WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();

    public AbstractServlet() {
        initAutowired();
    }

    private void initAutowired() {
        Field[] fields = this.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Autowired autowired = field.getAnnotation(Autowired.class);
                if (Objects.isNull(autowired)) {
                    return;
                }
                Object value = webApplicationContext.getBean(field.getName());
                field.set(this, value);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
